<template>
  <input type="file" @change="predict" />
  <br />
  <br />
  <img :src="imgSrc" width="500" />
</template>


<script>
import { reactive, toRefs } from "vue";
import * as tf from "@tensorflow/tfjs";
import { IMAGENET_CLASSES } from "./imagenet_classes";
import { file2img } from "./utils";

export default {
  setup: async () => {
    const MOBILENET_MODEL_PATH =
      "http://127.0.0.1:8080/mobilenet/web_model/model.json";

    const state = reactive({
      imgSrc: "",
    });

    const model = await tf.loadLayersModel(MOBILENET_MODEL_PATH);

    async function predict(e) {
      const file = e.target.files[0];
      const img = await file2img(file);
      state.imgSrc = img.src;
      const pred = tf.tidy(() => {
        const input = tf.browser
          .fromPixels(img)
          .toFloat()
          .sub(255 / 2)
          .div(255 / 2)
          .reshape([1, 224, 224, 3]);  
        console.log(model.predict, input);
        return model.predict(input);
      });

      const index = pred.argMax(1).dataSync()[0];
      console.log(`预测结果：${IMAGENET_CLASSES[index]}`);
    }

    const { imgSrc } = toRefs(state);

    return {
      imgSrc,
      predict,
    };
  },
};
</script>